package com.yfh.sharding.aop.aspect;


import com.yfh.sharding.utils.IPUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Objects;

/**
 * @author Anwen
 * @version 1.0
 * @date 2019-09-25 9:43
 * 日志生成切面类
 */
@Aspect
@Configuration
@Slf4j
public class LogAspect {



    @Pointcut("execution( * com.yfh.sharding.controller..*.*(..))")
    public void logPointCut() {
    }

    private long beforeTime;
    @Before("logPointCut()")
    public void doBefore(JoinPoint joinPoint) {
        try {
            beforeTime = System.currentTimeMillis();
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();
            log.info("           Url: " + request.getRequestURL().toString());
            log.info("   Http_method: " + request.getMethod());
            log.info("            Ip: " + IPUtil.getIpAddr(request));
            log.info("  Class_method: " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
            log.info("    Parameters: " + Arrays.toString(joinPoint.getArgs()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //返回
    @AfterReturning(returning = "ret", pointcut = "logPointCut()")
    public void doAfterReturning(Object ret) {
        long afterTime = System.currentTimeMillis();
        long time = afterTime - beforeTime;
        log.info("Return: {}, 执行时间：{}ms", ret, time);

    }







}